import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Advert.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/log_util.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/view/goods/view_goods.dart';
import 'package:flutter_chip/view/home/view_more.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/widget_sliver_delegate.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fsuper/fsuper.dart';

class HomePage extends StatefulWidget {
  var city;

  HomePage(this.city);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends StateWithLifecycle<HomePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List _myTabs = [];

  List _goodTabs = [
    {'label': '电路方案', 'type': 0},
    {'label': '毕设专题', 'type': 1},
  ];

  var items = [];

  bool isShowAds = false;
  PageController pageController;
  TabController tabController;
  int page = 0;
  var isPageCanChanged = true;

  @override
  void initState() {
    super.initState();
    pageController = PageController(initialPage: this.page);
    tabController = TabController(length: _goodTabs.length, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        onPageChange(tabController.index, p: pageController);
      }
    });
    _getAdverts();
  }

  @override
  void onResume() {
    super.onResume();
    _iniTabs();
  }

  @override
  Widget build(BuildContext context) {
    return NestedScrollView(
      headerSliverBuilder: _headerSliver,
      body: PageView(
        controller: pageController,
        onPageChanged: (index) {
          if (isPageCanChanged) {
            onPageChange(index);
          }
        },
        children: _goodTabs.map((item) {
          return GoodsPage(label: item['label']);
        }).toList(),
      ),
    );
  }

  List<Widget> _headerSliver(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        primary: true,
        automaticallyImplyLeading: false,
        floating: true,
        expandedHeight: isShowAds ? 200 : 0,
        pinned: true,
        flexibleSpace: FlexibleSpaceBar(
          collapseMode: CollapseMode.pin,
          background: isShowAds ? _sliverAds() : null,
        ),
      ),
      SliverGrid.count(
        crossAxisCount: 4,
        children: _myTabs.map((item) {
          return _toolWidget(item);
        }).toList(),
      ),
      SliverToBoxAdapter(
        child: Container(
          height: 1,
          color: Color(0xffEEEEEE),
        ),
      ),
      SliverPersistentHeader(
        pinned: true,
        floating: false,
        delegate: SliverAppBarDelegate(
          minHeight: 40,
          maxHeight: 40,
          child: Container(
            color: Colors.white,
            child: TabBar(
              isScrollable: true,
              onTap: (value) {
                pageController.jumpToPage(value);
              },
              indicator: BoxDecoration(),
              labelColor: Theme.of(context).accentColor,
              unselectedLabelColor: Colors.grey,
              tabs: _goodTabs.map((item) {
                return Container(
                    padding: EdgeInsets.all(2), child: Text(item['label']));
              }).toList(),
              controller: tabController,
            ),
          ),
        ),
      ),
      SliverToBoxAdapter(
        child: Divider(
          height: 1,
          color: Color(0xffDDDDDD),
        ),
      )
    ];
  }

  ///小工具按钮
  Widget _toolWidget(var item) {
    return FSuper(
      width: double.infinity,
      height: double.infinity,
      text: item['title'],
      textSize: 12,
      textWeight: FontWeight.w600,
      textAlignment: Alignment.bottomCenter,
      margin: EdgeInsets.all(10),
      child1: FSuper(
        width: 40,
        height: 40,
        backgroundColor: Color(item['color']),
        child1: Icon(Comm.iconMap[item['icon']], color: Colors.white),
        corner: Corner.all(20),
        shadowBlur: 4,
        shadowColor: Color(0xff999999),
      ),
      child1Margin: EdgeInsets.only(bottom: 6),
      onClick: () {
        if (null != item['path']) {
          var url = "${item['path']}";
          print('跳转链接：$url');
          Routers.router.navigateTo(
            context,
            url,
            transition: TransitionType.inFromRight,
          );
        } else {
          Navigator.of(context).push(RouteSlide(MorePage()));
        }
      },
    );
  }

  ///页面滑动监听
  onPageChange(int index, {PageController p, TabController t}) async {
    if (p != null) {
      //判断是哪一个切换
      isPageCanChanged = false;
      await pageController.animateToPage(index,
          duration: Duration(milliseconds: 500),
          curve: Curves.ease); //等待pageview切换完毕,再释放pageivew监听
      isPageCanChanged = true;
    } else {
      tabController.animateTo(index); //切换Tabbar
    }
  }

  ///轮播图控件
  Widget _sliverAds() {
    return Swiper(
      itemBuilder: (BuildContext context, int index) {
        Advert advert = items[index];
        return FSuper(
          backgroundImage: NetworkImage(Api.getUrl(advert.adsImage)),
          height: 230,
          width: double.infinity,
          child1: Container(
            color: Colors.black26,
            height: 40,
            width: double.infinity,
            alignment: Alignment.centerLeft,
            child: Text(
              advert.adsTitle,
              style: TextStyle(color: Colors.white),
            ),
          ),
          child1Alignment: Alignment.bottomCenter,
        );
      },
      onTap: (index) {
        String tagId = items[index].tagId;
        LogUtil.v(tagId, tag: "HOME");
        if (tagId.startsWith("GOODS")) {
          Routers.router.navigateTo(
            context,
            "${Routers.PAGE_GOOD_INFO}?goodsId=$tagId",
            transition: TransitionType.inFromRight,
          );
        }
      },
      pagination: SwiperPagination(alignment: Alignment.bottomRight),
      itemCount: items.length,
      itemHeight: 200,
      itemWidth: double.infinity,
      autoplay: false,
    );
  }

  ///获取tab
  void _iniTabs() async {
    List<String> tmpTabs = await SpUtils.get(SpUtils.SP_MYTAB, List<String>());
    setState(() {
      _myTabs.clear();
      if (tmpTabs.isEmpty) {
        _myTabs.addAll(Comm.allToolTabs.sublist(0, 7));
      } else {
        tmpTabs.forEach((value) {
          _myTabs.add(json.decode(value));
        });
      }
      _myTabs.add({
        'title': '更多',
        'color': 0xff525357,
        'icon': 'more_horiz',
      });
    });
  }

  ///获取广告
  void _getAdverts() {
    Http.get(Api.ADVERT_LIST, successCallBack: (data) {
      List list = json.decode(data).map((m) => Advert.fromJson(m)).toList();
      if (null != list && list.length > 0) {
        items.clear();
        setState(() {
          items.addAll(list);
          isShowAds = true;
        });
      }
    });
  }

  @override
  bool get wantKeepAlive => true;
}
